package com.company.cloud.user.modules.app.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Login;
import com.company.cloud.common.auth.annotation.StaffLogc;
import com.company.cloud.common.bean.*;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.redis.service.RedisUtils;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.PasswordUtils;
import com.company.cloud.customer.modules.api.response.AddrResponse;
import com.company.cloud.customer.modules.api.service.CustomerRemoteService;
import com.company.cloud.user.constant.ErrorUserEnum;
import com.company.cloud.user.constant.UserStateEnum;
import com.company.cloud.user.modules.api.models.UserModel;
import com.company.cloud.user.modules.api.response.UserSimple;
import com.company.cloud.user.modules.app.controller.req.CheckInvitationParam;
import com.company.cloud.user.modules.app.controller.req.UserPasswordUpdateParam;
import com.company.cloud.user.modules.app.service.UserAppService;
import com.company.cloud.user.modules.app.service.UserLoginService;
import com.company.cloud.user.modules.base.entity.ThirdUserInfo;
import com.company.cloud.user.modules.base.entity.UserInfo;
import com.company.cloud.user.modules.base.mapper.UserInfoMapper;
import com.company.cloud.user.modules.base.service.ThirdUserInfoService;
import com.company.cloud.user.modules.base.service.UserInfoService;
import com.company.cloud.user.modules.base.service.UserShareCodeService;
import com.company.cloud.user.modules.bus.producer.UserProducer;
import com.company.cloud.user.modules.cache.models.ArtistInfoModel;
import com.company.cloud.user.modules.cache.models.UserInvitationModel;
import com.company.cloud.user.modules.cache.service.UserCompanyCheckService;
import com.company.cloud.user.modules.cache.service.UserPermissionCacheService;
import com.company.cloud.user.modules.cache.utils.UserConvertUtils;
import com.company.cloud.user.modules.mgr.controller.req.UserUpdateParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Log4j2
@Login
@RestController
@RequestMapping("/app/user/info")
@Api(tags = "User_App_用户服务")
public class UserController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserShareCodeService userShareCodeService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UserLoginService userLoginService;

    @Autowired
    private UserAppService userAppService;

    @Autowired
    private UserInfoMapper userInfoMapper;
    /*  @Autowired
      private ArtistInfoService artistInfoService;*/
    @Autowired
    private ThirdUserInfoService thirdUserInfoService;

    @Autowired
    private UserPermissionCacheService userPermissionCacheService;

    @Autowired
    private UserCompanyCheckService userCompanyCheckService;

    @Autowired
    private CustomerRemoteService customerRemoteService;
    @Autowired
    private UserProducer userProducer;

    @GetMapping("/get")
    @ApiOperation(value = "获取用户基本信息", response = UserModel.class)
    public BaseResult get() {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        UserInfo entity = userInfoService.getById(userInfo.getId());
        UserModel user = UserConvertUtils.getUserModel(entity);
        final ArtistInfoModel artistInfo = userInfoMapper.selectByArtistInfoById(entity.getId());
        if (artistInfo != null) {
            user.setArtistNo(artistInfo.getArtistNo());
            user.setArtistImg(artistInfo.getHeadImg());
        }
        //获取地址
         BaseClientResult<List<AddrResponse>> addrList = customerRemoteService.getAddrList(userInfo.getId());
        List<AddrResponse> addrResponses=addrList.getData();
        addrResponses.forEach(m->{
            user.setAddr(m.getAddr());
        });
        return BaseResult.ok(user);
    }


    @GetMapping("/getUserSimpleById")
    @ApiOperation(value = "获取用户简单基本信息", response = UserSimple.class)
    public BaseResult getUserSimpleById(@RequestParam("id") Integer id) {
        if (CheckUtils.isEmpty(id)) {
            throw new BusinessException(BaseReturnEnum.PARAM_NULL);
        }
        UserInfo userInfo = userInfoService.getById(id);
        if (userInfo == null) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        UserSimple data = UserConvertUtils.getUserSimple(userInfo);
        return BaseResult.ok(data);

    }


    @GetMapping("/shareCode")
    @ApiOperation(value = "更改分享码", response = LoginUserInfo.class)
    public BaseResult shareCode() {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        return BaseResult.ok(userAppService.updateShareCode(userInfo));
    }

    @PostMapping("/update")
    @StaffLogc(title = "User_App_用户服务 、修改个人信息", action = "User_App_用户服务、修改个人信息", actionAdo = "User_App_用户服务")
    @ApiOperation(value = "修改个人信息", response = LoginUserInfo.class)
    public BaseResult update(@RequestBody UserUpdateParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        return BaseResult.ok(userAppService.update(params, userInfo));
    }

    @PostMapping("/updatePassword")
    @StaffLogc(title = "User_App_用户服务 、修改密码", action = "User_App_用户服务、修改密码", actionAdo = "User_App_用户服务")
    @ApiOperation(value = "修改密码", response = BaseResult.class)
    public BaseResult updatePassword(@RequestBody UserPasswordUpdateParam params) {
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        UserInfo user = userInfoService.getById(userInfo.getId());
        if (user == null) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        if (!UserStateEnum.NORMAL.getCode().equals(user.getUserState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        if (params.getOldPassword() != null && !"".equals(params.getOldPassword())) {
            if (!PasswordUtils.isCorrect(params.getOldPassword(), user.getSalt(), user.getPassword())) {
                throw new BusinessException(ErrorUserEnum.User_Password_Error);
            }
        }
        String[] passwords = PasswordUtils.getMd5Password(params.getNewPassword());
        UserInfo user2 = new UserInfo();
        user2.setId(user.getId());
        user2.setSalt(passwords[1]);
        user2.setPassword(passwords[0]);
        user2.addEditParam(userInfo);
        userInfoService.updateById(user2);
        return BaseResult.ok();
    }

    @PostMapping("/logout")
    @StaffLogc(title = "User_App_用户服务 、登出", action = "User_App_用户服务、登出", actionAdo = "User_App_用户服务")
    @ApiOperation(value = "登出", response = BaseResult.class)
    public BaseResult logout() {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        userLoginService.logout(userInfo);
        userProducer.userLogout(userInfo.getId(), userInfo.getToken(), "");
        return BaseResult.ok();
    }

    @PostMapping("/getPasswordInvitation")
    @ApiOperation(value = "获取密码邀请列表", response = UserInvitationModel.class)
    public BaseResult getPasswordInvitation(@RequestBody BasePageParam param) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        return BaseResult.ok(userAppService.getPasswordInvitation(param, userInfo));
    }

    @GetMapping("/getPasswordInvitationNew")
    @ApiOperation(value = "获取最新密码邀请", response = UserInvitationModel.class)
    public BaseResult getPasswordInvitationNew() {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        return BaseResult.ok(userAppService.getPasswordInvitationNew(userInfo));
    }

    @PostMapping("/checkInvitation")
    @ApiOperation(value = "接受邀请", response = BaseResult.class)
    public BaseResult checkInvitation(@RequestBody CheckInvitationParam param) {
        LoginSimpleUserInfo loginUserInfo = AuthContextUtils.getUser();
        UserInfo userInfo = userAppService.checkInvitation(param, loginUserInfo);
        ThirdUserInfo thirdUserInfo = null;
        if (CheckUtils.hasInt(loginUserInfo.getThirdId())) {
            thirdUserInfo = thirdUserInfoService.getById(loginUserInfo.getThirdId());
        }

        //刷新用户缓存
        LoginUserInfo data = userLoginService.login(userInfo, thirdUserInfo, loginUserInfo.getToken(), null);
        userPermissionCacheService.loadPermissionRoleCache(data.getCompanyNo());
        return BaseResult.ok(data);
    }

//	@GetMapping("/textShowComb")
//	@ApiOperation(value="测试随机数组",response =BaseResult.class)
//	public BaseResult textShowComb() {
//		userCompanyCheckService.restCombs(1);
//		return BaseResult.ok();
//	}


}
